import type { MqttClient, OnMessageCallback } from 'mqtt';

//@ts-ignore
import * as mqtt from 'mqtt/dist/mqtt.min.js';
import { uuid } from 'vue-uuid';

class MQTT {
  type: string; // 客户端分类（非必须）
  url: string; // mqtt地址
  client!: MqttClient;
 
  constructor(type: string) {
    this.type= type;
    this.url = import.meta.env.VITE_MQTT_URL_WS;// ws方式必须ws结尾
  }
 
  //初始化mqtt
  init() {
    const options = {
      clean: true,
      clientId: this.type+ "_" , // 客户端分类唯一   + uuid.v1()
      username: import.meta.env.VITE_MQTT_USERNAME,
      password: import.meta.env.VITE_MQTT_PASSWORD,
      connectTimeout: 30000, // 超时时间
    };
 
    this.client = mqtt.connect(this.url, options);
 
    this.client.on('error', (error: any) => {
      console.log(this.url + "异常中断");
    });
 
    this.client.on('reconnect', (error: Error) => {
      console.log(this.url + "重新连接");
    });
  }
 
  //取消订阅
  unsubscribes(topic: string) {
    this.client.unsubscribe(topic, (error: Error) => {
      if (!error) {
        console.log(topic + '取消订阅成功');
      } else {
        console.log(topic + '取消订阅失败');
      }
    });
  }
 
  //连接
  link(topic: string) {
    this.client.on('connect', () => {
      this.client.subscribe(topic, (error: any) => {
        if (!error) {
          console.log(topic + '订阅成功');
        } else {
          console.log(topic + '订阅失败');
        }
      });
    });
  }
 
  //收到的消息
  get(callback: OnMessageCallback) {
    this.client.on('message', callback);
  }
 
  //结束链接
  over() {
    this.client.end();
  }
}
export default MQTT;